package cn.service.impl;

import cn.dao.CodePayDao;
import cn.service.CodePayService;
import cn.util.EncryptUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.apache.http.client.HttpClient;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("codePayService")
public class CodePayServiceImpl implements CodePayService {
    static final Logger logger = LoggerFactory.getLogger(HttpClient.class);

    @Resource
    CodePayDao codePayDao;


    /**
     * 登陆接口
     *
     * @param map
     * @return
     * @throws Exception
     */
    public Map<String, Object> login(Map<String, Object> map) throws Exception {
        Map<String, Object> result = new HashMap<>();
        //加密密码
        map.put("userpwd", EncryptUtil.encode(map.get("userpwd").toString()));
        //每次登陆生成 回调秘钥
        map.put("userkey", EncryptUtil.encode(String.valueOf((int) ((Math.random() * 9 + 1) * 100000)) + "*&^+_!@"));
        UsernamePasswordToken token = new UsernamePasswordToken(map.get("userbh").toString(), map.get("userpwd").toString());
        //当前用户线程
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            Session session = subject.getSession();
            result = codePayDao.login(map);
        } catch (UnknownAccountException ex) {
            result.put("state", 1001);
            result.put("message", "用户不存在！");
        } catch (IncorrectCredentialsException ex) {
            result.put("state", 1002);
            result.put("message", "密码错误！");
        } catch (ExcessiveAttemptsException ex) {
            result.put("state", 1003);
            result.put("message", "账号或密码错误次数过多,请稍后重试！");
        } catch (AuthenticationException ex) {
            result.put("state", 1004);
            result.put("message", ex.getMessage());// 自定义报错信息
        } catch (Exception ex) {
            ex.printStackTrace();
            result.put("state", 1005);
            result.put("message", "内部错误，请重试！");
        }
        return result;
    }

    /**
     * 获取收款信息
     *
     * @param map
     * @return
     */
    public Map<String, Object> gettimemoney(Map<String, Object> map) {
        return codePayDao.gettimemoney(map);
    }

    /**
     * 获取域名信息
     *
     * @param map
     * @return
     */
    public List<Map<String, Object>> geturl(Map<String, Object> map) {
        return codePayDao.geturl(map);
    }

    /**
     * 更新 收款单状态
     *
     * @param map
     * @return
     */
    public int updatereceivables(Map<String, Object> map) {
        int result = 0;
        //获取订单信息
        Map<String, Object> order = codePayDao.getorder(map);
        //推送给客户
        if (codePayDao.updatereceivables(map) == 1) {
            HttpUtils.post(order.get("urlname").toString(), order);
            result = 1;
        }
        return result;
    }

//    /**
//     * 获取可用金额  代码废弃
//     *
//     * @param map
//     * @return
//     */
//    public String getmoney(Map<String, Object> map) {
//        Object resultmoney;
//        boolean sfcz = false;
//
//        DecimalFormat df = new DecimalFormat("##0.00");
//        DecimalFormatSymbols dfs = new DecimalFormatSymbols();
//        dfs.setDecimalSeparator('.');
//        df.setDecimalFormatSymbols(dfs);
//
//        ArrayList list = new ArrayList();
//        //优惠价格
//        if(map.get("gdtype").equals("1")){
//            map.put("money",Integer.parseInt(map.get("money").toString())-1);
//        }
//
//        List<Map<String, Object>> listmoney = codePayDao.getmoney(map);
//
//        //更新超时支付金额   默认30分钟
//        codePayDao.updatemoney(map);
//        for (int i = 1; i <= 99; i++) {
//            if (listmoney != null) {
//                for (Map<String, Object> money : listmoney) {
//                    if (Double.parseDouble(money.get("money").toString()) == (i * 0.01)) {
//                        sfcz = true;
//                        System.out.println(i * 0.01 + "---");
//                        break;
//                    } else {
//                        sfcz = false;
//                    }
//                }
//            }
//            if (!sfcz) {
//                list.add(i * 0.01);
//            }
//        }
//
//
//        int x = (int) (Math.random() * list.size());
//
//        resultmoney = map.get("money");
////        //优惠价格
////        if (map.get("gdtype").equals("1")) {
////            resultmoney = ((Integer.valueOf(resultmoney.toString())) - 1) + (Double) list.get(x);
////
////            return nf.format(resultmoney);
////        } else {
//            resultmoney = (Integer.valueOf(resultmoney.toString())) + (Double) list.get(x);
//            //惩罚价格
//            return df.format(resultmoney);
//       // }
//    }

    @Override
    public Map<String,Object> createorder(Map<String, Object> map) {
        Object resultmoney;
        boolean sfcz = false;

        DecimalFormat df = new DecimalFormat("##0.00");
        DecimalFormatSymbols dfs = new DecimalFormatSymbols();
        dfs.setDecimalSeparator('.');
        df.setDecimalFormatSymbols(dfs);

        ArrayList list = new ArrayList();
        //优惠价格
        if(map.get("gdtype").equals("1")){
            map.put("money",Integer.parseInt(map.get("money").toString())-1);
        }

        List<Map<String, Object>> listmoney = codePayDao.getmoney(map);

        //更新超时支付金额   默认30分钟
        codePayDao.updatemoney(map);
        for (int i = 1; i <= 99; i++) {
            if (listmoney != null) {
                for (Map<String, Object> money : listmoney) {
                    if (Double.parseDouble(money.get("money").toString()) == (i * 0.01)) {
                        sfcz = true;
                        System.out.println(i * 0.01 + "---");
                        break;
                    } else {
                        sfcz = false;
                    }
                }
            }
            if (!sfcz) {
                list.add(i * 0.01);
            }
        }


        int x = (int) (Math.random() * list.size());

        resultmoney = map.get("money");
        resultmoney = (Integer.valueOf(resultmoney.toString())) + (Double) list.get(x);

        //获取的可用金额
        map.put("money",df.format(resultmoney));
        int state = 0;
        List<Map<String, Object>> sourse = codePayDao.iseorder(map);
        if (sourse.size() > 0) {
            //订单号重复
            state = 1006;
        } else {
            state = codePayDao.createorder(map);
        }
        map.put("state",state);
        map.remove("sql");
        return map;
    }
    public String kuaidi(String code){
        String response="";
        String okenV2="";
        String com="";
        Map<String, String> header=new HashMap<>();
        header.put("Client-Ip","[ranip]");
        header.put("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.80 Safari/537.36 Core/1.47.277.400 QQBrowser/9.4.7658.400");
        header.put("cookie","BIDUPSID=132FB974F9FF486ADDACC0A5A712EEF7; PSTM=1602568133; BAIDUID=132FB974F9FF486ADEB71892F0682036:FG=1; BDUSS=2dEdTlPb3FqRkw3eX5MNW1kLWZDLS1yQjhnUm5BQkJ2UDE1OUpXQjdSY2xVd1ZnRVFBQUFBJCQAAAAAAAAAAAEAAAB6-Ho9WUlNT0hPTkdDSEVOR18AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACXG3V8lxt1fZ; BDUSS_BFESS=2dEdTlPb3FqRkw3eX5MNW1kLWZDLS1yQjhnUm5BQkJ2UDE1OUpXQjdSY2xVd1ZnRVFBQUFBJCQAAAAAAAAAAAEAAAB6-Ho9WUlNT0hPTkdDSEVOR18AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACXG3V8lxt1fZ; BAIDUID_BFESS=132FB974F9FF486ADEB71892F0682036:FG=1; __yjs_duid=1_bd9c326e63693f1de3ea9b26395e6d201608861298888; ab_sr=1.0.0_ZDMzMjQ5ZGVlMmEzNGI1OTQ1YzFjZGZlYzk0YzU3YjMwOTUyYTU4MzAwY2FlNjRlMGQzZWJkYWJhYzJlNDM1MjY4ZTU3YTZiNjhiNWZmZmFiOGY0YjFjNTkzMTlhZjg5Mjc2OWJjMGRhYTlhM2Y4ZjA0MzM1OTA4NTllNWZmYzM=; BDRCVFR[tiixOo0cjw_]=mk3SLVN4HKm; delPer=0; PSINO=6; BDORZ=FFFB88E999055A3F8A630C64834BD6D0; H_PS_PSSID=1448_33222_33306_33235_31253_33343_33313_33312_33311_33310_33309_33321_33308_33307_33144_33265; BDRCVFR[feWj1Vr5u3D]=I67x6TjHwwYf0; BA_HECTOR=858k8h25000l0k25ki1fualg80r");
        response=HttpUtils.get("https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=1&rsv_idx=2&ch=&tn=baiduhome_pg&bar=&wd="+code+"&rsv_spt=1&oq=550009521127898&rsv_pq=895a832c000005a6&rsv_t=1fe9ETqNVYCwTixSlpZwA4cFEhogS76H6r2ZkG8bfSCrMB%2Fr5u6qlh0%2B9kye14yHe%2FEZ&rqlang=cn&rsv_btype=t&rsv_dl=tb", header);
        okenV2=getSubString(response,"okenV2=","\"");
        com=getSubString(response,"com:'","'");
        response=HttpUtils.get("https://express.baidu.com/express/api/express?query_from_srcid=&isBaiduBoxApp=10002&isWisePc=10020&tokenV2="+okenV2+"&cb=jQuery1102006219520766524633_1608865287656&appid=10002&com="+com+"&nu="+code+"&vcode=&token=&qid=8ed20b24000179c9&_=1608865287660", header);
        response="{"+getSubString(response,"({","})")+"}";
        return JSON.toJSONString(JSON.parseObject(response), SerializerFeature.PrettyFormat);
    }
    /**
     * 取两个文本之间的文本值
     * @param text 源文本 比如：欲取全文本为 12345
     * @param left 文本前面
     * @param right 后面文本
     * @return 返回 String
     */
    public static String getSubString(String text, String left, String right) {
        String result = "";
        int zLen;
        if (left == null || left.isEmpty()) {
            zLen = 0;
        } else {
            zLen = text.indexOf(left);
            if (zLen > -1) {
                zLen += left.length();
            } else {
                zLen = 0;
            }
        }
        int yLen = text.indexOf(right, zLen);
        if (yLen < 0 || right == null || right.isEmpty()) {
            yLen = text.length();
        }
        result = text.substring(zLen, yLen);
        return result;
    }
}
